package com.sunday.pinxinghui.model.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sunday.common.base.BaseFragment;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.SharePerferenceUtils;
import com.sunday.common.widgets.CircleImageView;
import com.sunday.common.widgets.NoScrollGridView;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.base.BaseApplication;
import com.sunday.pinxinghui.entity.Member;
import com.sunday.pinxinghui.entity.OrderNums;
import com.sunday.pinxinghui.model.WebViewActivity;
import com.sunday.pinxinghui.model.account.PurseActivity;
import com.sunday.pinxinghui.model.mine.AddressListActivity;
import com.sunday.pinxinghui.model.mine.CollectionListActivity;
import com.sunday.pinxinghui.model.mine.CouponListActivity;
import com.sunday.pinxinghui.model.mine.MemberCenterActivity;
import com.sunday.pinxinghui.model.mine.RecomendListActivity;
import com.sunday.pinxinghui.model.mine.ServicePlaceListActivity;
import com.sunday.pinxinghui.model.mine.SettingActivity;
import com.sunday.pinxinghui.model.mine.SignActivity;
import com.sunday.pinxinghui.model.mine.UserInfoActivity;
import com.sunday.pinxinghui.model.order.OrderListActivity;
import com.sunday.pinxinghui.model.order.OrderRefundActivity;
import com.sunday.pinxinghui.network.ApiClient;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import q.rorbin.badgeview.Badge;
import q.rorbin.badgeview.QBadgeView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.sunday.pinxinghui.network.ApiClient.CUSTOMER_URL;


/**
 * Created by 刘涛 on 2017/8/3.
 */

public class MineFragment extends BaseFragment {


    @Bind(R.id.user_logo)
    CircleImageView userLogo;
    @Bind(R.id.user_name)
    TextView userName;
    @Bind(R.id.user_level)
    TextView userLevel;
    @Bind(R.id.menu_order_1)
    TextView menuOrder1;
    @Bind(R.id.menu_order_2)
    TextView menuOrder2;
    @Bind(R.id.menu_order_3)
    TextView menuOrder3;
    @Bind(R.id.menu_order_4)
    TextView menuOrder4;
    @Bind(R.id.menu_order_5)
    TextView menuOrder5;
    @Bind(R.id.menu_order_6)
    TextView menuOrder6;
    @Bind(R.id.grid_view)
    NoScrollGridView gridview;
    @Bind(R.id.title)
    TextView title;


    private List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
    private SimpleAdapter adapter;
    private int[] icon = {R.mipmap.purse, R.mipmap.user_order_coupon,
            R.mipmap.member_rec, R.mipmap.member, R.mipmap.user_order_collection, R.mipmap.service, R.mipmap.user_order_address,
            R.mipmap.send, R.mipmap.signin};

    private Member member;

    private String[] iconName = {"我的钱包", "我的卡券", "我要推荐", "会员中心"
            , "我的收藏", "我的客服", "我的地址", "配送点", "签到积分"};

    public static MineFragment newInstance() {
        MineFragment fragment = new MineFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.mine_fragment, container, false);
        ButterKnife.bind(this, rootView);
        title.requestFocus();
        title.setFocusable(true);
        title.setFocusableInTouchMode(true);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //StatusBarUtil.setTransparentForImageView(getActivity(), null);
        getMenus();
        getUserInfo();
        initView();
    }

    public List<Map<String, Object>> getMenus() {
        for (int i = 0; i < icon.length; i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("image", icon[i]);
            map.put("text", iconName[i]);
            dataList.add(map);
        }
        return dataList;
    }

    long memberId;

    public void getUserInfo() {
        memberId = BaseApplication.getInstance().getMember().getId();
        Call<ResultDO<Member>> call = ApiClient.getApiAdapter().getMember(memberId);
        call.enqueue(new Callback<ResultDO<Member>>() {
            @Override
            public void onResponse(Call<ResultDO<Member>> call, Response<ResultDO<Member>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    member = response.body().getResult();
                    SharePerferenceUtils.getIns(mContext).saveOAuth(member);
                    BaseApplication.getInstance().setMember(member);
                    initUserInfo();
                    getOrderNums();
                }

            }

            @Override
            public void onFailure(Call<ResultDO<Member>> call, Throwable t) {

            }
        });
    }

    private void getOrderNums() {
        Call<ResultDO<OrderNums>> call = ApiClient.getApiAdapter().getOrderCount(member.getId());
        call.enqueue(new Callback<ResultDO<OrderNums>>() {
            @Override
            public void onResponse(Call<ResultDO<OrderNums>> call, Response<ResultDO<OrderNums>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    updateOrderNums(response.body().getResult());
                }

            }

            @Override
            public void onFailure(Call<ResultDO<OrderNums>> call, Throwable t) {

            }
        });
    }

    private void initUserInfo() {
        if (member == null) {
            return;
        }
        Glide.with(mContext)
                .load(member.getLogo())
                .error(R.mipmap.logo_default)
                .into(userLogo);
        userName.setText(member.getNickName() == null ? "新用户" : member.getNickName());
        userLevel.setText(member.getIsVip() == 0 ? "普通用户" : "品行会员");

    }

    Badge badge1, badge2, badge3, badge4, badge5, badge6;

    private void updateOrderNums(OrderNums orderNums) {
        if (orderNums.getWaitPayCount() >= 0) {
            if (badge1 == null) {
                badge1 = new QBadgeView(mContext).bindTarget(menuOrder1).setBadgeNumber(orderNums.getWaitPayCount());
            } else {
                badge1.setBadgeNumber(orderNums.getWaitPayCount());
            }
            badge1.setShowShadow(false);
            badge1.setBadgeBackground(ContextCompat.getDrawable(mContext, R.color.main_color), true);
            badge1.setGravityOffset(-3, 8, true);
            badge1.setBadgeTextSize(10, true);
        }
        if (orderNums.getWaitSendCount() >= 0) {
            if (badge2 == null) {
                badge2 = new QBadgeView(mContext).bindTarget(menuOrder2).setBadgeNumber(orderNums.getWaitSendCount());
            } else {
                badge2.setBadgeNumber(orderNums.getWaitSendCount());
            }

            badge2.setShowShadow(false);
            badge2.setGravityOffset(-3, 8, true);
            badge2.setBadgeBackground(ContextCompat.getDrawable(mContext, R.color.main_color), true);
            badge2.setBadgeTextSize(10, true);
        }
        if (orderNums.getWaitConfirmCount() >= 0) {
            if (badge3 == null) {
                badge3 = new QBadgeView(mContext).bindTarget(menuOrder3).setBadgeNumber(orderNums.getWaitConfirmCount());
            } else {
                badge3.setBadgeNumber(orderNums.getWaitConfirmCount());
            }

            badge3.setShowShadow(false);
            badge3.setGravityOffset(-3, 8, true);
            badge3.setBadgeBackground(ContextCompat.getDrawable(mContext, R.color.main_color), true);
            badge3.setBadgeTextSize(10, true);
        }
        if (orderNums.getWaitSinceCount() >= 0) {
            if (badge4 == null) {
                badge4 = new QBadgeView(mContext).bindTarget(menuOrder4).setBadgeNumber(orderNums.getWaitSinceCount());
            } else {
                badge4.setBadgeNumber(orderNums.getWaitSinceCount());
            }

            badge4.setShowShadow(false);
            badge4.setGravityOffset(-3, 8, true);
            badge4.setBadgeBackground(ContextCompat.getDrawable(mContext, R.color.main_color), true);
            badge4.setBadgeTextSize(10, true);
        }
        if (orderNums.getWaitCommentCount() >= 0) {
            if (badge5 == null) {
                badge5 = new QBadgeView(mContext).bindTarget(menuOrder5).setBadgeNumber(orderNums.getWaitCommentCount());
            } else {
                badge5.setBadgeNumber(orderNums.getWaitCommentCount());
            }

            badge5.setShowShadow(false);
            badge5.setGravityOffset(-3, 8, true);
            badge5.setBadgeBackground(ContextCompat.getDrawable(mContext, R.color.main_color), true);
            badge5.setBadgeTextSize(10, true);
        }
        if (orderNums.getWaitRefundCount() >= 0) {
            if (badge6 == null) {
                badge6 = new QBadgeView(mContext).bindTarget(menuOrder6).setBadgeNumber(orderNums.getWaitRefundCount());
            } else {
                badge6.setBadgeNumber(orderNums.getWaitRefundCount());
            }
            badge6.setShowShadow(false);
            badge6.setGravityOffset(-3, 8, true);
            badge6.setBadgeBackground(ContextCompat.getDrawable(mContext, R.color.main_color), true);
            badge6.setBadgeTextSize(10, true);
        }

    }


    private void initView() {
        String[] from = {"image", "text"};
        int[] to = {R.id.item_image, R.id.item_text};
        adapter = new SimpleAdapter(mContext, dataList, R.layout.item_my, from, to);
        gridview.setAdapter(adapter);
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0://我的钱包
                        intent = new Intent(mContext, PurseActivity.class);
                        startActivity(intent);
                        break;
                    case 1://我的卡券
                        intent = new Intent(mContext, CouponListActivity.class);
                        startActivity(intent);
                        break;
                    case 2://我要推荐
                        intent = new Intent(mContext, RecomendListActivity.class);
                        startActivity(intent);
                        break;
                    case 3://会员中心
                        intent = new Intent(mContext, MemberCenterActivity.class);
                        startActivity(intent);
                        break;
                    case 4://我的收藏
                        intent = new Intent(mContext, CollectionListActivity.class);
                        startActivity(intent);
                        break;
                    case 5://我的客服
                        intent = new Intent(mContext, WebViewActivity.class);
                        intent.putExtra("title", "客服");
                        intent.putExtra("url", CUSTOMER_URL);
                        startActivity(intent);
                        break;
                    case 6://我的地址
                        intent = new Intent(mContext, AddressListActivity.class);
                        startActivity(intent);
                        break;
                    case 7://配送点
                        intent = new Intent(mContext, ServicePlaceListActivity.class);
                        startActivity(intent);
                        break;
                    case 8://签到积分
                        intent = new Intent(mContext, SignActivity.class);
                        startActivity(intent);
                        break;
                }
            }
        });

    }

    @OnClick({R.id.user_info_layout, R.id.check_all_order, R.id.menu_order_1, R.id.menu_order_2, R.id.menu_order_3,
            R.id.menu_order_4, R.id.menu_order_5, R.id.menu_order_6, R.id.menu_set})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.user_info_layout:
                intent = new Intent(mContext, UserInfoActivity.class);
                startActivity(intent);
                break;
            case R.id.check_all_order:
                intent = new Intent(mContext, OrderListActivity.class);
                startActivity(intent);
                break;
            case R.id.menu_order_1:
                intent = new Intent(mContext, OrderListActivity.class);
                intent.putExtra("page", 1);
                startActivity(intent);
                break;
            case R.id.menu_order_2:
                intent = new Intent(mContext, OrderListActivity.class);
                intent.putExtra("page", 2);
                startActivity(intent);
                break;
            case R.id.menu_order_3:
                intent = new Intent(mContext, OrderListActivity.class);
                intent.putExtra("page", 3);
                startActivity(intent);
                break;
            case R.id.menu_order_4:
                intent = new Intent(mContext, OrderListActivity.class);
                intent.putExtra("page", 4);
                startActivity(intent);
                break;
            case R.id.menu_order_5:
                intent = new Intent(mContext, OrderListActivity.class);
                intent.putExtra("page", 6);
                startActivity(intent);
                break;
            case R.id.menu_order_6:
                intent = new Intent(mContext, OrderRefundActivity.class);
                startActivity(intent);
                break;
            case R.id.menu_set:
                intent = new Intent(mContext, SettingActivity.class);
                startActivity(intent);
                break;
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        getUserInfo();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
